package com.errands.cn.controller;

import com.errands.cn.entity.Recomment;
import com.errands.cn.entity.User;
import com.errands.cn.services.RecommentService;
import com.errands.cn.utils.Json;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/recommend")
public class RecommentController {

    @Autowired
    private RecommentService recommentService;

    @PostMapping("/add")
    public Json addRecomment(Recomment recomment, HttpServletRequest request){
        Json json = new Json();
        User user = (User) request.getSession().getAttribute("user");
        if (user == null){
            json.setMsg("你还没有登录，无法进行评论");
            return json;
        }
        if(recommentService.orderRecommentByUserCount(user.getUid(),recomment.getoId())){
            json.setMsg("你已经评论过该条订单，请不要重复发表评论");
            return json;
        }
        recomment.setDate(new Date());
        recomment.setUid(user.getUid());
        try {
            recommentService.save(recomment);
            json.setSuccess(true);
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("发表评论失败");
        }
        return json;
    }

    @GetMapping("/delete")
    public boolean deleteRecomment(Integer id){
        try {
            recommentService.delete(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据订单id获得评论
     * @param pageNum
     * @param pageSize
     * @param oid
     * @return
     */
    @GetMapping("/select")
    public PageInfo<Recomment> selectRecommed(Integer pageNum,Integer pageSize,Integer oid){
        PageInfo<Recomment> pageInfo = recommentService.findRecommentByOrder(oid,pageNum,pageSize);
        return pageInfo;
    }

}
